package com.lry.client;

import com.lry.proto.ClassInfo;
import com.lry.proto.Request;
import com.lry.proto.Response;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.*;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/9/16
 */
@Slf4j
public class RpcClient {

    private String host;
    private int port;
    private Channel channel;
    private EventLoopGroup group;
    private Map<String,Object> respMap;
    private Bootstrap bootstrap;
    public RpcClient(String host,int port){
        this.host = host;
        this.port = port;
        this.respMap = new ConcurrentHashMap<>();
        initBootstrap();
        connectToServer(host,port);
    }

    private void initBootstrap(){
        group = new NioEventLoopGroup();
        final ClientHandler clientHandler = new ClientHandler(this);
        bootstrap = new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new ObjectEncoder());
                pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                pipeline.addLast(clientHandler);
            }
        });
    }

    public void connectToServer(String host, Integer port) {
        String key = host+":"+port;
        CountDownLatch cdl = new CountDownLatch(1);
        //连接
        bootstrap.connect(host,port).addListener((ChannelFuture futureListener) -> {
            final EventLoop eventLoop = futureListener.channel().eventLoop();
            if (!futureListener.isSuccess()) {
                //连接tcp服务器不成功 3s后重连
                log.info(key + "连接失败!在3s之后准备尝试重连!");
                eventLoop.schedule(() -> connectToServer(host, port), 3, TimeUnit.SECONDS);
            }else {
                this.channel = futureListener.channel();
                log.info("连接"+key+"成功,channel={}", this.channel);
                cdl.countDown();
            }
        });
        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void shutdown(){
        this.group.shutdownGracefully();
    }

    public Map<String, Object> getRespMap() {
        return respMap;
    }

    public Object invokeRpc(ClassInfo classInfo) {
        String uuid = UUID.randomUUID().toString();
        Request request = new Request(uuid,classInfo);

        Response response = new Response(uuid,null);
        respMap.put(uuid,response);

        log.info("客户端写给服务器：{}，channel={}",request,this.channel);
        this.channel.writeAndFlush(request);

        synchronized (response){
            try {
                response.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return response.getMsg();
    }
}
